import os
import json
import tempfile
import subprocess
from .api import client, retry_api

def transcript_audio(video_file: str, format: str = 'text') -> str | dict:
    from pydub import AudioSegment

    if not os.path.exists(video_file):
        raise FileNotFoundError("Video file does not exist")

    aac_path = tempfile.mktemp(suffix=".aac")
    mp3_path = tempfile.mktemp(suffix=".mp3")
    try:
        subprocess.check_call(["ffmpeg", "-y", "-i", video_file, "-vn", "-acodec", "copy", aac_path])

        audio_segment = AudioSegment.from_file(aac_path)
        audio_segment = audio_segment[:10 * 60 * 1000]
        audio_segment.export(mp3_path, format="mp3")
        audio_path = mp3_path

        if format == 'json':
            data = json.loads(subprocess.check_output(["curl", "https://api.openai.com/v1/audio/transcriptions",
              "-H", "Authorization: Bearer " + client.api_key,
              "-H", "Content-Type: multipart/form-data",
              "-F", "file=@" + audio_path,
              "-F", "timestamp_granularities[]=segment",
              "-F", "model=whisper-1",
              "-F", "response_format=verbose_json"]))
            return data
        else:
            assert format == 'text'
            transcript = retry_api(client.audio.transcriptions.create,
                file=open(audio_path, "rb"),
                model="whisper-1",
            )
            return transcript.text
    finally:
        if os.path.exists(aac_path):
            os.unlink(aac_path)
        if os.path.exists(mp3_path):
            os.unlink(mp3_path)

if __name__ == '__main__':
    transcript_audio('/home/bate/Videos/bilibili/fav_1106514255/愿望幽灵 Minus ft. 诗岸.mp4')
